package com.szh.mysobproject.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.text.HtmlCompat
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.TimeUtils
import com.szh.mysobproject.databinding.MomentMsgListItemBinding
import com.szh.mysobproject.model.msg.MomentMsg
import com.szh.mysobproject.util.setFixOnClickListener

/**
 * @author : create by  szh
 * @date : 2022/7/12 13:50
 * @desc :墨鱼评论列表消息
 */

class MomentMsgAdapter(private val adapterDelegate: AdapterDelegate) :
    PagingDataAdapter<MomentMsg.Content, MomentMsgAdapter.MomentMsgViewHolder>(MomentMsgDiffCallBack()) {

    class MomentMsgDiffCallBack : DiffUtil.ItemCallback<MomentMsg.Content>() {

        override fun areItemsTheSame(
            oldItem: MomentMsg.Content,
            newItem: MomentMsg.Content
        ): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(
            oldItem: MomentMsg.Content,
            newItem: MomentMsg.Content
        ): Boolean {
            return oldItem == newItem
        }

    }

    inner class MomentMsgViewHolder(val binding: MomentMsgListItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onBindViewHolder(holder: MomentMsgViewHolder, position: Int) {
        val binding = holder.binding
        val itemView = holder.itemView
        val ivAvatar = binding.ivAvatar
        val cbNickName = binding.cbNickName
        val tvDesc = binding.tvDesc
        val tvReplyMsg = binding.tvReplyMsg
        val tvChildReplyMsg = binding.tvChildReplyMsg
        val item = getItem(position) ?: return
        itemView.setFixOnClickListener {
            adapterDelegate.onItemClick(it, position)
        }
        ivAvatar.loadAvatar(false, item.avatar)
        cbNickName.text = item.nickname
        val sdf = TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm")
        tvDesc.text = TimeUtils.getFriendlyTimeSpanByNow(item.createTime, sdf)
        tvReplyMsg.text = item.content
        tvChildReplyMsg.text = HtmlCompat.fromHtml(item.title, HtmlCompat.FROM_HTML_MODE_LEGACY)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MomentMsgViewHolder {
        val binding =
            MomentMsgListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MomentMsgViewHolder(binding)
    }
}